import click

from watchlist import app, db 
from watchlist.models import User, Movie


# 初始化数据库命令
# 注册为命令
@app.cli.command()
# 设置选项
@click.option('--drop', is_flag=True, help='Create after drop.')
def initdb(drop):
    """Initialize the database."""
    # 判断: 是否输入选项
    if drop:
        click.echo('drop all over')
        db.drop_all()
    # 创建所有表(不重复)
    db.create_all()
    # 输出提示信息
    click.echo('Initialized database')

# 创建模拟数据命令
@app.cli.command()
def forge():
    """Generate  fake data."""
    # 清空数据
    users = User.query.all()
    for u in users:
        db.session.delete(u)
    movies = Movie.query.all()
    for m in movies:
        db.session.delete(m)
    db.session.commit()

    # 创建所有表(不重复)
    db.create_all()

    # 全局的两个变量移到到这个函数内
    name = '小鸣'
    movies = [
        {'title': '庇护所：阿尔卑斯山求生记', 'year': '1988'},
        {'title': '塔可夫斯基：在电影中祈祷', 'year': '1989'},
        {'title': '欢迎来到车臣', 'year': '1993'},
        {'title': '少年邦', 'year': '1994'},
        {'title': '索莱', 'year': '1996'},
        {'title': '八百', 'year': '1996'},
        {'title': '春江水暖', 'year': '1999'},
        {'title': '影里', 'year': '1999'},
        {'title': '夏日国度', 'year': '2008'},
        {'title': '托马索', 'year': '2012'},
    ]

    user = User(name=name)
    db.session.add(user)
    for m in movies:
        movie = Movie(title=m['title'], year = m['year'])
        db.session.add(movie)

    db.session.commit()
    click.echo('Done.')

# 生成管理员账户命令
@app.cli.command()
@click.option('--username', prompt=True, help='Ther username user to login.')
@click.option('--password', prompt=True)
def admin(username, password):
    """Create  user"""
    db.create_all();

    user = User.query.first()
    if user is not None:
        click.echo("Updating user ...")
        user.username=username
        user.set_password(password) # 设置密码
    else:
        click.echo("Creating user ...")
        user = User(username=username, name='Admin')
        user.set_password(password)
        db.session.add(user)
    db.session.commit()  # 提交会话
    click.echo('Done.')
 